import { Random } from 'mockjs';
import multer, { diskStorage, memoryStorage } from 'multer';
import path from 'path';

export const IMGS_PATH = path.join(__dirname, '../ufile/imgs_save');
export const OTHERS_PATH = path.join(__dirname, '../ufile/file');

// 存储配置
const storage_memory = memoryStorage();
const storage_store = diskStorage({
	// //设置存储路径
	destination: (req, file, cb) => {
		cb(null, IMGS_PATH);
	},
	//设置存储的文件名
	filename: (req, file, cb) => {
		console.log('filename:', file); //打印结果如下图
		//获取文件的扩展名
		const { originalname, fieldname } = file;
		const extname = path.extname(originalname);
		const name = `file-${Date.now()}-${Random.word(7)}${extname}`;
		cb(null, name);
	},
});

// 限制
const limits = {
	fileSize: 5 * 1024 * 1024, //设置单个文件最大为 10 * 1024 K
};

export const uploadImg = multer({
	storage: storage_store,
	limits,
}).single('file');

export const uploadArray = multer({
	storage: storage_store,
	limits,
}).array('files', 9);

export const uploadAny = multer({
	dest: OTHERS_PATH,
}).any();
